package org.yzz.auth.interceptors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.yzz.auth.annotation.RonghuaPermission;
import org.yzz.base.utils.LoginContext;
import org.yzz.org.domain.Employee;
import org.yzz.org.service.IEmployeeService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private IEmployeeService service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 通过 Header 获取到前端的 token ，因为 前端的 token 是放在 Header 里面的
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            System.out.println("没有传入token");
            // 提示用户登录
            response.getWriter().print("{\"success\":false,\"msg\":\"NoLogin\"}");
            return false;
        }
        Employee user = (Employee)LoginContext.map.get(token);// 根据前端的 token 来取后端的 value
        if (Objects.isNull(user)) {
            System.out.println("对象取值错误");
            // 提示用户登录
            response.getWriter().print("{\"success\":false,\"msg\":\"NoLogin\"}");
            return false;
        }

        //对于url路径的权限控制
// 1．判断用户访问的这个资源需要权限不?
        HandlerMethod methodHandle = (HandlerMethod) handler;
        RonghuaPermission methodAnnotation = methodHandle.getMethodAnnotation(RonghuaPermission.class);
        if (Objects.nonNull(methodAnnotation)) {
// 2．如果需要权限判断用户是否有权限
            //2.1 首先拿到用户的权限通过用户拿
            List<String> list = service.queryPermissionByUserId(user.getId());
            // 2.2在拿当前资源的权限/emp/list(资源权限)emp:list(用户的权限)
            Method method = methodHandle.getMethod();
            String mp = method.getDeclaringClass().getSimpleName() + ":" + method.getName();
            // 2.3比较用户的权限和资源的权限﹑如果比对上就放行否则拦截
            if (!list.contains(mp)) {
                System.out.println("无权访问....");
                response.getWriter().print("{\"success\":false,\"msg\":\"NoPermission\"}");
                return false;
            }
        }
        return true;
    }
}
